package com.zouxian.processor;

import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import com.zouxian.phantom.TestPhantomJsDriver;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

public class MyProcessor8_login implements PageProcessor {

	private Site site = Site.me().setRetryTimes(3).setSleepTime(0).setTimeOut(3000);

	// 用来存储cookie信息
	private Set<Cookie> cookies;

	@Override
	public void process(Page page) {
		// 获取用户的id
		page.putField("user", page.getHtml().$("#ui-login a:first-child","allText").toString());

		

	}

	// 使用 selenium 来模拟用户的登录获取cookie信息
	public void login() {
		//设置PhantomJS配置路径
		//System.setProperty("phantomjs.binary.path", "D:\\developTools\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");		
		//System.setProperty("phantomjs.binary.path", "D:\\crawl.js");
		DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();
		//WebDriver driver = new PhantomJSDriver();
		//WebDriver driver=TestPhantomJsDriver.getPhantomJSDriver();
		WebDriver driver=new ChromeDriver();
		driver.get(
				"https://i.huanqiu.com/");

		driver.findElement(By.name("email")).clear();

		// 在******中填你的用户名
		driver.findElement(By.name("email")).sendKeys("13650563957");

		driver.findElement(By.name("password")).clear();
		// 在*******填你密码
		driver.findElement(By.name("password")).sendKeys("huanqiu124508");

		// 模拟点击登录按钮
		driver.findElement(By.name("submit")).click();

		// 获取cookie信息
		cookies = driver.manage().getCookies();
		driver.close();
	}

	@Override
	public Site getSite() {

		// 将获取到的cookie信息添加到webmagic中
		for (Cookie cookie : cookies) {
			site.addCookie(cookie.getName().toString(), cookie.getValue().toString());
		}

		return site.addHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1");
	}

	public static void main(String[] args) {
		MyProcessor8_login miai = new MyProcessor8_login();

		// 调用selenium，进行模拟登录
		miai.login();
		Spider.create(miai).addUrl("http://www.huanqiu.com/").run();
	}
}
